package online.niuma.xiaocubao.utils;

import com.alibaba.fastjson2.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * @author 一颗蛋50斤
 * IntelliJ IDEA
 */
@Slf4j
@Component
public class QiniuUtils {

    private static final String URL = "http://verification.niuma.online/";

    @Value("${qiniu.bucket}")
    private String  bucket;
    @Value("${qiniu.accessKey}")
    private  String accessKey;
    @Value("${qiniu.secretKey}")
    private  String secretKey;

    public String upload(MultipartFile file, String fileName) {
        Configuration config = new Configuration(Region.huanan());
        UploadManager uploadManager = new UploadManager(config);
        try {
            byte[] bytes = file.getBytes();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(bytes, fileName, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
                return URL + putRet.key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                log.error(r.toString());
                try {
                    log.error(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (UnsupportedEncodingException ex) {
            //ignore
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "上传失败";
    }

    /**
     * 在七牛云删除文件
     *
     * @param fileKey 文件的路径
     */
    @Async
    public void delete(String fileKey) {
        // 定义默认头像的地址
        String defaultKey = "img/niumaHead.png";
        Configuration config = new Configuration(Region.huanan());
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, config);
        // 获取到文件的 key 值
        String key = fileKey.split(URL)[1];
        // 如果要删除的文件是默认的头像则不删除
        // 直接返回 true
        if (key.equals(defaultKey)) {
            return;
        }
        try {
            // 删除文件
            bucketManager.delete(bucket, key);
        } catch (QiniuException e) {
            log.error(String.valueOf(e.code()));
            log.error(e.response.toString());
        }
    }
}
